package cn.supermarket.service.impl;

import cn.supermarket.pojo.dto.RefundAddNew;
import cn.supermarket.pojo.dto.RefundSimple;
import cn.supermarket.pojo.entity.Refund;
import cn.supermarket.pojo.vo.RefundDetailsVO;
import cn.supermarket.ex.ServiceException;
import cn.supermarket.mapper.RefundMapper;
import cn.supermarket.service.iservice.IRefundService;
import cn.supermarket.service.iservice.IVIPService;
import cn.supermarket.utils.GetDateTime;
import cn.supermarket.utils.GetInfoUtils;
import cn.supermarket.utils.SnowFlakeGenerateIdWorker;
import cn.supermarket.web.State;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
public class RefundServiceImpl implements IRefundService {

    @Autowired
    RefundMapper refundMapper;

    @Autowired
    GetDateTime getDateTime;

    @Autowired
    GetInfoUtils getInfoUtils;

    @Autowired
    IVIPService VipService;

    /**
     * 添加记录
     *
     * @param refundAddNew
     * @return
     */
    @Transactional
    @Override
    public Long insert(RefundAddNew refundAddNew) {
        System.out.println("refundAddNew = " + refundAddNew);
        SnowFlakeGenerateIdWorker snowFlakeGenerateIdWorker = new SnowFlakeGenerateIdWorker(10L,20L);
        Long id = snowFlakeGenerateIdWorker.nextId();
        LocalDateTime now = LocalDateTime.now();
        if(refundAddNew.getRefundType().equals("会员卡")){
                VipService.addAmount((""+refundAddNew.getBankNumber()),refundAddNew.getMoney());
        }
        Refund refund = new Refund();
        BeanUtils.copyProperties(refundAddNew, refund);
        refund.setId(id);
        //退款编号
        String number = now.toString();
        refund.setNumber(number);
        refund.setLastUpdateTime(now);
        refund.setCreateDate(now);
        refund.setIsDisplay(1);
        refund.setIsEnable(0);
        refund.setIsCancel(0);
        refund.setHandler(getInfoUtils.getUserInfo().getUsername());
        Long row = refundMapper.insert(refund);
        if (row != 1) {
            throw new ServiceException(State.ERR_UNKNOWN_ERROR,"未知错误导致信息插入失败，请稍后再试");
        }
        return row;
    }

    /**
     * 修改启用
     *
     * @param id
     * @param isEnabled
     * @return
     */
    @Transactional
    @Override
    public int updateIsEnable(Long id, Integer isEnabled) {
        RefundSimple refundSimple = refundMapper.selectById(id);
        if (refundSimple == null) {
            throw new ServiceException(State.ERR_NOT_FOUND, "该退款单不存在");
        }
        if (isEnabled.equals(refundSimple.getIsEnable())) {
            throw new ServiceException(State.ERR_REPEAT_UPDATE, "该操作为无效的重复操作");
        }
        int row = refundMapper.updateIsEnable(id, isEnabled);
        LocalDateTime time = LocalDateTime.now();
        int row2 = refundMapper.updateLastUpdateTime(time, id);
        if (row != 1 && row2 != 1) {
            throw new ServiceException(State.ERR_UNKNOWN_ERROR, "未知错误导致修改失败，请稍后再试");
        }
        return row;
    }

    /**
     * 修改可见
     *
     * @param id
     * @param isDisplay
     * @return
     */
    @Transactional
    @Override
    public int updateIsDisplay(Long id, Integer isDisplay) {
        RefundSimple refundSimple = refundMapper.selectById(id);
        if (refundSimple == null) {
            throw new ServiceException(State.ERR_NOT_FOUND, "该退款单不存在");
        }
        if (isDisplay.equals(refundSimple.getIsDisplay())) {
            throw new ServiceException(State.ERR_REPEAT_UPDATE, "该操作为无效的重复操作");
        }
        int row = refundMapper.updateIsDisplay(id, isDisplay);
        LocalDateTime time = LocalDateTime.now();
        int row2 = refundMapper.updateLastUpdateTime(time, id);
        if (row != 1 && row2 != 1) {
            throw new ServiceException(State.ERR_UNKNOWN_ERROR, "未知错误导致修改失败，请稍后再试");
        }
        return row;
    }

    /**
     * 修开作废
     *
     * @param id
     * @return
     */
    @Transactional
    @Override
    public int updateIsCancel(Long id) {
        RefundSimple refundSimple = refundMapper.selectById(id);
        if (refundSimple == null) {
            throw new ServiceException(State.ERR_NOT_FOUND, "该退款单不存在");
        }

        int row = refundMapper.updateIsCancel(id);
        LocalDateTime time = LocalDateTime.now();
        int row2 = refundMapper.updateLastUpdateTime(time, id);
        if (row != 1 && row2 != 1) {
            throw new ServiceException(State.ERR_UNKNOWN_ERROR, "因网络波动或退款单已锁定导致修改失败，请稍后再试");
        }
        return row;
    }

    /**
     * 修改备注
     *
     * @param id
     * @param other
     * @return
     */
    @Transactional
    @Override
    public int updateOther(Long id, String other) {
        RefundSimple refundSimple = refundMapper.selectById(id);
        if (refundSimple == null) {
            throw new ServiceException(State.ERR_NOT_FOUND, "该退款单不存在");
        }
        int row = refundMapper.updateOther(id, other);
        LocalDateTime time = LocalDateTime.now();
        int row2 = refundMapper.updateLastUpdateTime(time, id);
        if (row != 1 && row2 != 1) {
            throw new ServiceException(State.ERR_UNKNOWN_ERROR, "因网络波动或退款单已锁定导致修改失败，请稍后再试");
        }
        return row;
    }

    /**
     * 根据单号查询
     *
     * @param number
     * @return
     */
    @Override
    public RefundDetailsVO selectByNumber(String number) {
        RefundDetailsVO refundDetailsVO = refundMapper.selectByNumber(number);
        if (refundDetailsVO == null) {
            throw new ServiceException(State.ERR_NOT_FOUND, "该退款单不存在");
        }
        return refundDetailsVO;
    }

    /**
     * 根据订单编号查询
     *
     * @param orderNumber
     * @return
     */
    @Override
    public RefundDetailsVO selectByOrderNumber(String orderNumber) {
        RefundDetailsVO refundDetailsVO = refundMapper.selectByOrderNumber(orderNumber);
        if (refundDetailsVO == null) {
            throw new ServiceException(State.ERR_NOT_FOUND, "没有找到该退款记录，请确认单号再次尝试");
        }
        return refundDetailsVO;
    }


    /**
     * 按照日期查询（范围）
     *
     * @param dateStart
     * @param dateEnd
     * @return
     */
    @Override
    public List<RefundDetailsVO> selectListByDatetime(Date dateStart, Date dateEnd) {
        List<RefundDetailsVO> refundList;
        if(dateStart == null||dateEnd == null){
            LocalDateTime newDateStart = LocalDateTime.now().minusMinutes(1);
            LocalDateTime newEndTime = LocalDateTime.now();
            refundList = refundMapper.selectListByDatetime(newDateStart, newEndTime);
        }else {
            refundList = refundMapper.selectListByDatetime(getDateTime.getDateStart(dateStart), getDateTime.getDateEnd(dateEnd));
        }
        if (refundList == null || refundList.size() == 0) {
            throw new ServiceException(State.ERR_NOT_FOUND, "该时间段内无相应的退款记录");
        }
        return refundList;
    }

    /**
     * 根据供货商（即退款人）查询
     *
     * @param supplier
     * @return
     */
    @Override
    public List<RefundDetailsVO> selectBySupplier(String supplier) {
        List<RefundDetailsVO> refundList = refundMapper.selectBySupplier(supplier);
        if (refundList == null || refundList.size() == 0) {
            throw new ServiceException(State.ERR_NOT_FOUND, "没有关于此供货商的退款记录");
        }
        return refundList;
    }

    /**
     * 根据买家查询
     *
     * @param collect
     * @return
     */
    @Override
    public List<RefundDetailsVO> selectByCollect(String collect) {
        List<RefundDetailsVO> refundList = refundMapper.selectByCollect(collect);
        if (refundList == null || refundList.size() == 0) {
            throw new ServiceException(State.ERR_NOT_FOUND, "没有关于此供货商的退款记录");
        }
        return refundList;
    }
}
